package com.xkstream.client.presenter;

import android.content.Intent;

import com.google.gson.Gson;
import com.xkstream.client.api.UserApi;
import com.xkstream.client.api.UserService;
import com.xkstream.client.application.Application;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.BasePresenterImpl;
import com.xkstream.client.entity.User;
import com.xkstream.client.rx.RxHelper;
import com.xkstream.client.rx.RxObserver;
import com.xkstream.client.utils.PreferenceUtils;

import java.util.Map;

import io.reactivex.functions.Consumer;

/**
 * Created by xiaoyi on 2017/8/24.
 */

public class UserPresenter extends BasePresenterImpl implements UserContract.Presenter {
    private UserService userService;

    private UserContract.View view;

    public UserPresenter(UserContract.View view) {
        this.view = view;
        userService = UserApi.getInstance().service;
    }


    @Override
    public void userLogin(Map<String, Object> params) {
        view.showLoading();
        userService.userLogin(params).compose(RxHelper.toUI())
                .doOnNext(new Consumer<BaseData<User>>() {
                    @Override
                    public void accept(BaseData<User> userBaseData) throws Exception {
                       /* if (userBaseData.getCode() == 1) {
                            NimHelper.logout();
                            NimHelper.login(new LoginInfo(userBaseData.getData().getUser_code(),
                                    userBaseData.getData().getToken()));
                        }*/
                    }
                }).subscribe(new RxObserver<BaseData<User>>(this) {
            @Override
            protected void onSuccess(BaseData<User> userBaseData) {
                view.hideLoading();
                if (userBaseData.getCode() == 1) {
                    PreferenceUtils.putString(PreferenceUtils.USER,
                            new Gson().toJson(userBaseData.getData()));
                    Application.setUser(userBaseData.getData());
                    view.loginSuccess(userBaseData.getData());
                } else {
                    view.loginFailed(userBaseData.getCode(), userBaseData.getMsg());
                }
            }

            @Override
            protected void onFail(String message) {
                view.hideLoading();
                view.showError(message);
            }
        });

    }


}
